package com.audaque.jadmin.system.shiro;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.alibaba.fastjson.JSON;
import com.audaque.jadmin.common.model.MessageModel;

/**
 * @Description :匿名过滤器，配置的链接无需登录，其他的需要登录。首先页面提示，然后跳转到登录页
 * @FileName: OnLineFilter.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年10月26日 下午2:43:09
 * @Version:V1.00
 */
public class AnonymousFilter extends AbstractAccessControlFilter {

	private static final Logger LOG = Logger.getLogger(AnonymousFilter.class);

	@Override
	protected boolean _isAccessAllowed(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
			Object mappedValue) throws Exception {

		String uri = getUri(httpRequest);

		// 排除js,css,png,gif(不好哇)
		if (uri.endsWith(".js") || uri.endsWith(".json") || uri.endsWith(".css") || uri.endsWith(".png")
				|| uri.endsWith(".jpg") || uri.endsWith(".gif")) {
			return true;
		}

		LOG.info(String.format("AccessAllowed:当前访问的URL是： %s ", uri));

		boolean match = isMatch(uri);

		if (match) {
			return true;
		}

		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			return true;
		}
		return false;
	}

	@Override
	protected boolean _onAccessDenied(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
			throws Exception {

		String uri = getUri(httpRequest);

		LOG.info(String.format("AccessDenied:当前访问的URL是： %s ", uri));

		boolean match = isMatch(uri);

		boolean ajax = isAjax(httpRequest);

		/**
		 * 不是匿名URL并且是ajax请求，就给出没登录的提示
		 */
		if (!match && ajax) {
			PrintWriter writer = httpResponse.getWriter();
			MessageModel messageModel = new MessageModel(false, "请登录");
			messageModel.setResult(getLoginUrl());
			writer.print(JSON.toJSONString(messageModel));
			return false;
		}

		return false;
	}

}
